package com.bw.ssm.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bw.ssm.pojo.JUser;
import com.bw.ssm.service.JUserService;

@Controller
public class IndexController {

	@Autowired
	private JUserService service;

	@RequestMapping("/toLogin")
	public String toLogin(HttpServletRequest request,
			HttpServletResponse response, Model model, JUser user) {

//		deleteCookie(request,response,"username");
//		deleteCookie(request,response,"password");
		return "login";
	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request,
			HttpServletResponse response, Model model, JUser user) throws UnsupportedEncodingException {
		if (user.getUsername()==null || "".equals(user.getUsername())) {
			model.addAttribute("error", "请输入用户名");
			return "login";
		}
		if (user.getPassword()==null || "".equals(user.getPassword())) {
			model.addAttribute("error", "请输入密码");
			return "login";
		}
		List<JUser> l = service.list(user);
		if (l != null && l.size() > 0) {
			JUser u = l.get(0);
			if (user.getPassword().equals(u.getPassword())) {
				HttpSession session = request.getSession();
				session.setAttribute("user", u);
				//将用户信息保存到cookie中
				setCookie(request, response, u);
				model.addAttribute("error", "登录成功");
			} else {
				model.addAttribute("error", "密码错误");
				return "login";
			}
		} else {
			model.addAttribute("error", "未找到此人");
			return "login";
		}

//		return "redirect:index";
		return "login";
//		return "redirect:toLogin";
	}

	public void setCookie(HttpServletRequest request,
			HttpServletResponse response,JUser user) throws UnsupportedEncodingException {
		
		// 编码，解决中文乱码
		String str = URLEncoder.encode(user.getUsername(), "utf-8");
		// 设置 name 和 url cookie
		Cookie username = new Cookie("username", str);
		Cookie password = new Cookie("password", user.getPassword());
		Cookie testcookie = new Cookie("testcookie", "test");

		// 设置cookie过期时间为24小时。
//		username.setMaxAge(60 * 60 * 24);
//		password.setMaxAge(60 * 60 * 24);
		password.setMaxAge(20 );
		
		username.setMaxAge(60 * 60 );
		//设置后前台看不到
//		username.setDomain("");
		username.setPath("/");
		String comment = URLEncoder.encode("保存用户名", "utf-8");
		username.setComment("this is username");
		//加密后访问不到
//		username.setSecure(true);
		//设置true后js读不到cookie，默认false
		username.setHttpOnly(false);
		username.setVersion(1);

		// 在响应头部添加cookie
		response.addCookie(username);
		response.addCookie(password);
		response.addCookie(testcookie);
	}
	/**
	 * 删除cookie
	 * @param request
	 * @param response
	 * @param cookieName
	 */
	public void deleteCookie(HttpServletRequest request,
			HttpServletResponse response,
			String cookieName){
		Cookie cookie = null;
		   Cookie[] cookies = null;
		   // 获取当前域名下的cookies，是一个数组
		   cookies = request.getCookies();
		   if( cookies != null ){
		      for (int i = 0; i < cookies.length; i++){
		         cookie = cookies[i];
		         if((cookie.getName( )).compareTo(cookieName) == 0 ){
		        	 //将cookie设为立即过期
		            cookie.setMaxAge(0);
		            response.addCookie(cookie);
		         }
		      }
		  }
	}

	@RequestMapping("/index")
	public String index(Model model) {

		return "index";
	}

	@RequestMapping("/getMenu")
	public String getMenu(Model model, HttpServletResponse response) {

		String json = "[{ " + "\"id\":1," + "\"text\":\"顶层菜单\","
				+ "\"children\":[" + "{" + "\"id\":1," + "\"text\":\"微博系统\","
				+ "\"state\":\"closed\", " + "\"children\":[" + "{"
				+ "	\"text\":\"用户列表\"," + "	\"checked\":true,"
				+ "	\"url\":\"/wbuser/list\"" + "}," + "{"
				+ "	\"text\":\"好友列表\"," + "	\"checked\":true,"
				+ "	\"url\":\"/wbfrend/list\"" + "}," + "{"
				+ "	\"text\":\"陌生人列表\"," + "	\"checked\":true,"
				+ "	\"url\":\"/wbmsr/list\"" + "}" + "]" + "}," + "{"
				+ "\"id\":2," + "\"text\":\"系统管理\"," + "\"state\":\"closed\", "
				+ "\"children\":[{" + "	\"text\":\"用户列表\","
				+ "	\"url\":\"/student/list\"" + "}]" + "}," + "{"
				+ "\"id\":3," + "\"text\":\"商品管理\"," + "\"state\":\"open\","
				+ "\"children\":[{" + "	\"text\":\"商品\","
				+ "	\"checked\":true," + "	\"url\":\"/goods/list\"" + "},{"
				+ "	\"text\":\"商品类型\"," + "	\"checked\":true,"
				+ "	\"url\":\"/user/list\"" + "}" + "]" + "}]" + "}]";
		response.setContentType("text/html;charset=utf-8");
		try {
			// logger.info("无分页信息json串：" + json);
			response.getWriter().print(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
